from rest_framework import viewsets, filters, permissions, status, serializers
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from django.db import transaction
from django_filters.rest_framework import DjangoFilterBackend
from datetime import date, datetime, timedelta
from django.shortcuts import get_object_or_404
from rest_framework.exceptions import ValidationError
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt

from .models import Patient, Diagnosis
from .serializers import PatientSerializer, DiagnosisSerializer
from apps.doctor.models import DiagnosisTemplate


class PatientViewSet(viewsets.ModelViewSet):
    """患者视图集"""
    queryset = Patient.objects.all()
    serializer_class = PatientSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['gender']
    search_fields = ['name', 'id_number', 'phone']
    ordering_fields = ['created_at', 'updated_at']
    ordering = ['-created_at']
    
    @action(detail=True, methods=['post'], url_path='call')
    def call_patient(self, request, pk=None):
        """叫号"""
        patient = self.get_object()
        if patient.status != 'waiting':
            return Response({"error": f"患者 {patient.name} 当前状态为 {patient.get_status_display()}, 无法叫号。"}, 
                           status=status.HTTP_400_BAD_REQUEST)
        
        patient.status = 'diagnosing'
        patient.save()
        
        return Response({"message": f"已叫号：{patient.name}"}, status=status.HTTP_200_OK)
    
    @action(detail=True, methods=['post'], url_path='treat')
    def treat_patient(self, request, pk=None):
        """接诊"""
        patient = self.get_object()
        if patient.status != 'diagnosing':
            return Response({"error": f"患者 {patient.name} 当前状态为 {patient.get_status_display()}, 无法接诊。"}, 
                           status=status.HTTP_400_BAD_REQUEST)
        
        # 这里可以添加更多的接诊逻辑
        
        return Response({"message": f"已接诊：{patient.name}"}, status=status.HTTP_200_OK)


class DoctorActionsViewSet(viewsets.ViewSet):
    """包含医生特定操作的视图集"""
    permission_classes = [permissions.IsAuthenticated]
    # permission_classes = [permissions.IsAuthenticated, IsDoctorUser] # 可添加医生角色权限

    @action(detail=False, methods=['get'], url_path='dashboard-stats')
    def get_dashboard_stats(self, request):
        """获取医生工作台首页的统计数据"""
        today = timezone.now().date()
        
        # 待诊人数 (状态为 waiting 的患者)
        waiting_count = Patient.objects.filter(status='waiting').count()
        
        # 今日接诊 (今天的诊断记录数)
        today_diagnosed = Diagnosis.objects.filter(
            created_at__date=today
        ).count()
        
        # 总接诊量 (所有诊断记录数)
        total_diagnosed = Diagnosis.objects.all().count()
        
        # 今日预约 (今天挂号的患者)
        today_appointments = Patient.objects.filter(
            registration_time__date=today
        ).count()

        stats_data = {
            'waiting_count': waiting_count,
            'today_diagnosed': today_diagnosed,
            'total_diagnosed': total_diagnosed,
            'today_appointments': today_appointments
        }
        return Response(stats_data)

    @action(detail=False, methods=['get'], url_path='waiting-patients')
    def get_waiting_patients(self, request):
        """获取当前登录医生的待诊患者列表"""
        waiting_patients = Patient.objects.filter(
            status='waiting',
        ).order_by('registration_time')

        serializer = PatientSerializer(waiting_patients, many=True)
        return Response({
            'count': waiting_patients.count(),
            'next': None,
            'previous': None,
            'results': serializer.data
        })

    @action(detail=False, methods=['post'], url_path='diagnosis')
    @transaction.atomic
    def save_diagnosis(self, request):
        """保存诊断记录并更新患者状态"""
        serializer = DiagnosisSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            try:
                diagnosis_instance = serializer.save()
                patient = diagnosis_instance.patient

                if patient.status == 'waiting' or patient.status == 'diagnosing':
                    patient.status = 'diagnosed'
                    if not patient.doctor:
                         patient.doctor = request.user
                    patient.save()
                else:
                    return Response({"warning": f"患者 {patient.name} 当前状态为 {patient.get_status_display()}, 未更新状态。"}, status=status.HTTP_200_OK)

                return Response(serializer.data, status=status.HTTP_201_CREATED)
            except Exception as e:
                 print(f"Error saving diagnosis: {e}")
                 return Response({"error": "保存诊断时发生内部错误"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class DiagnosisHistoryViewSet(viewsets.ReadOnlyModelViewSet):
    """
    诊断历史视图集
    """
    queryset = Diagnosis.objects.all()
    serializer_class = DiagnosisSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        patient_id = self.request.query_params.get('patient_id')
        if patient_id:
            return Diagnosis.objects.filter(patient_id=patient_id).order_by('-created_at')
        return Diagnosis.objects.none()

@api_view(['GET'])
def dashboard_stats(request):
    """获取仪表盘统计数据"""
    today = timezone.now().date()
    tomorrow = today + timedelta(days=1)
    
    # 待诊人数
    waiting_count = Patient.objects.filter(status='waiting').count()
    
    # 今日接诊
    today_diagnosed = Patient.objects.filter(
        registration_time__date=today,
        status__in=['diagnosing', 'diagnosed', 'completed']
    ).count()
    
    # 总接诊量
    total_diagnosed = Patient.objects.filter(
        status__in=['diagnosing', 'diagnosed', 'completed']
    ).count()
    
    # 今日预约
    today_appointments = Patient.objects.filter(
        registration_time__date=today
    ).count()
    
    return Response({
        'waiting_count': waiting_count,
        'today_diagnosed': today_diagnosed,
        'total_diagnosed': total_diagnosed,
        'today_appointments': today_appointments
    })

@api_view(['GET'])
def waiting_patients(request):
    """获取待诊患者列表"""
    patients = Patient.objects.filter(status='waiting').order_by('registration_time')
    data = [{
        'id': p.id,
        'name': p.name,
        'gender': p.gender,
        'age': p.age,
        'registration_time': p.registration_time.strftime('%Y-%m-%d %H:%M:%S'),
        'department': '门诊',  # 这里可以根据实际情况修改
        'doctor': p.doctor.username if p.doctor else '',
        'status': p.status
    } for p in patients]
    return Response({'results': data})

@api_view(['POST'])
@permission_classes([AllowAny])  # 暂时允许所有访问，方便测试
@csrf_exempt  # 暂时豁免 CSRF，方便测试
def call_patient(request, patient_id):
    """叫号"""
    try:
        patient = Patient.objects.get(id=patient_id)
        if patient.status != 'waiting':
            return Response({'error': '患者状态不正确'}, status=status.HTTP_400_BAD_REQUEST)
        
        patient.status = 'diagnosing'
        patient.save()
        
        return Response({'success': True})
    except Patient.DoesNotExist:
        return Response({'error': '患者不存在'}, status=status.HTTP_404_NOT_FOUND)

@api_view(['GET'])
def patient_diagnoses(request, patient_id):
    """获取患者诊断历史"""
    try:
        diagnoses = Diagnosis.objects.filter(patient_id=patient_id).order_by('-created_at')
        data = [{
            'id': d.id,
            'created_at': d.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'diagnosis': d.diagnosis,
            'chief_complaint': d.chief_complaint,
            'treatment_plan': d.treatment_plan,
            'doctor_name': d.doctor.username if d.doctor else ''
        } for d in diagnoses]
        return Response({
            'results': data,
            'count': len(data)
        })
    except Exception as e:
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
def treat_patient(request, patient_id):
    """接诊"""
    try:
        patient = Patient.objects.get(id=patient_id)
        if patient.status != 'diagnosing':
            return Response({'error': '患者状态不正确'}, status=status.HTTP_400_BAD_REQUEST)
        
        patient.status = 'diagnosed'
        patient.save()
        
        return Response({'success': True})
    except Patient.DoesNotExist:
        return Response({'error': '患者不存在'}, status=status.HTTP_404_NOT_FOUND)

@api_view(['POST'])
def save_diagnosis(request):
    """保存诊断"""
    try:
        data = request.data
        print("接收到的诊断数据:", data)  # 调试日志
        
        # 验证必填字段
        required_fields = ['patient', 'chief_complaint', 'diagnosis', 'treatment_plan']
        for field in required_fields:
            if not data.get(field):
                return Response(
                    {'error': f'缺少必填字段: {field}'}, 
                    status=status.HTTP_400_BAD_REQUEST
                )
        
        # 获取患者
        try:
            patient = Patient.objects.get(id=data['patient'])
        except Patient.DoesNotExist:
            return Response(
                {'error': '患者不存在'}, 
                status=status.HTTP_404_NOT_FOUND
            )
        
        # 创建诊断记录
        diagnosis = Diagnosis.objects.create(
            patient=patient,
            doctor=request.user,
            chief_complaint=data['chief_complaint'],
            present_illness=data.get('present_illness', '无'),
            past_history=data.get('past_history', '无'),
            allergy_history=data.get('allergy_history', '无'),
            physical_examination=data.get('physical_examination', '无特殊'),
            diagnosis=data['diagnosis'],
            treatment_plan=data['treatment_plan']
        )
        
        # 更新患者状态
        patient.status = 'completed'
        patient.save()
        
        return Response({
            'success': True, 
            'id': diagnosis.id,
            'message': '诊断记录保存成功'
        })
    except Exception as e:
        print("保存诊断时出错:", str(e))  # 调试日志
        return Response(
            {'error': f'保存诊断失败: {str(e)}'}, 
            status=status.HTTP_400_BAD_REQUEST
        ) 